﻿#include "amplprogramwindow.h"
#include "ui_amplprogramwindow.h"
#include <mainwindow.h>
extern intListener doorStatus;
amplprogramwindow::amplprogramwindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::amplprogramwindow)
{
    ui->setupUi(this);
    mpShadeWindow = new QWidget(this);
    QStringList  labels;
    labels <<QStringLiteral("编号")<<QStringLiteral("是否默认") << QStringLiteral("程序名称") << QStringLiteral("时长") << QStringLiteral("步骤数")<<QStringLiteral("热盖温度(℃)")<<QStringLiteral("创建时间")<<QStringLiteral("备注")<<QStringLiteral("操作");
    ui->tableWidget->setColumnCount(9);
    ui->tableWidget->setHorizontalHeaderLabels(labels);
    ui->tableWidget->resizeColumnsToContents(); //根据内容调整列宽
    ui->tableWidget->setColumnHidden(1, true); // 隐藏第2列
    ui->tableWidget->horizontalHeader()->setStretchLastSection(true);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableWidget->setStyleSheet("background-color: rgb(235,243,255);");
    QHeaderView* headerView = ui->tableWidget->verticalHeader();
    headerView->setHidden(false); //false 显示行号列  true Hide
#ifdef Q_OS_ANDROID
    int fontId = QFontDatabase::addApplicationFont(":/FontStyle/AlibabaPuHuiTi-3-55-Regular.ttf");
    if (fontId != -1) {
        QStringList fontFamilies = QFontDatabase::applicationFontFamilies(fontId);
        if (!fontFamilies.isEmpty()) {
            QString familyName = fontFamilies.first();
            QFont font(familyName, 18); // 创建一个QFont对象，设置字体名称和默认大小

            // 使用setFont方法设置字体，传入QFont对象
            ui->tableWidget->setFont(font);
            ui->pushButton->setFont(font);
            ui->addAmplStepBtn->setFont(font);


            // 如果需要为其他按钮设置不同的大小，可以创建新的QFont对象
            QFont smallerFont(familyName, 16);
            ui->returnMainWinBtn->setFont(smallerFont);
            ui->pushButton_5->setFont(smallerFont);

        }
    }
#endif
}

//页面关闭时调用
amplprogramwindow::~amplprogramwindow()
{
    delete ui;
}

void amplprogramwindow::showEvent(QShowEvent *event){
    logClient = loghelper::getInstance();
    tcpClient = TcpClient::getInstance();
    if(doorStatus.get()==0)
    {
        ui->pushButton_5->setText("        打开仓门");
    }
    else
    {
        ui->pushButton_5->setText("        关闭仓门");
    }

    RefreshTableData();
    refShadeWindow();
    event->accept();
}

void amplprogramwindow::resizeEvent(QResizeEvent *event){
    refShadeWindow();
}

void amplprogramwindow::refShadeWindow(){
    if(mpShadeWindow){
        mpShadeWindow->close();
    }

    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString sql="Select * From IsFirstStartUp";
    query.exec(sql);

    bool isFirst=false;
    int guideStatus;
    while (query.next()) {
        isFirst = query.value("IsFirst").toString()=="0";
        guideStatus = query.value("GuideStatus").toInt();
    }
    query.clear();

    if(isFirst){
        if(guideStatus==1)//扩增程序
        {
            mpShadeWindow = new QWidget(this);
            QString str("QWidget{background-color:rgba(0,0,0,0.6);}");   //0.6代表透明度，根据需要自行调整
            mpShadeWindow->setStyleSheet(str);
            QRect rect = this->geometry();
            int screenWidth = rect.width();  // 屏幕宽度
            int screenHeight = rect.height();  // 屏幕高度
            mpShadeWindow->setGeometry(0, 0,screenWidth,screenHeight);    //遮罩窗口位置

            QRect btnRect= ui->addAmplStepBtn->frameGeometry();

            QLabel *label=new QLabel("2/4程序",mpShadeWindow);
            QPalette palette;
            palette.setColor(QPalette::WindowText, QColor(255,255,255));
            QFont font=label->font();
            font.setPointSize(24);
            label->setFont(font);
            label->setPalette(palette);
            label->setGeometry(btnRect.x()-40,screenHeight-160,180,30);
            label->setStyleSheet("background-color:rgba(0,0,0,0);");

            QPushButton * btnSkipThis = new QPushButton("跳过当前引导",mpShadeWindow);
            btnSkipThis->setGeometry(btnRect.x()-110,screenHeight-120,120,40);
            btnSkipThis->setStyleSheet("border-radius: 8px; background-color:#FFFFFF");

            QObject::connect(btnSkipThis, &QPushButton::clicked,[this](){
                QSqlDatabase db = dbHelper::openConnection();
                QSqlQuery query(db);

                QString sql="Update IsFirstStartUp set GuideStatus=2";
                query.exec(sql);
                query.clear();

                refShadeWindow();
            });

            QPushButton * btnSkipAll = new QPushButton("跳过全部引导",mpShadeWindow);
            btnSkipAll->setGeometry(btnRect.x()+20,screenHeight-120,120,40);
            btnSkipAll->setStyleSheet("border-radius: 8px; background-color:#2F42CD");

            QObject::connect(btnSkipAll, &QPushButton::clicked,[this](){
                QSqlDatabase db = dbHelper::openConnection();
                QSqlQuery query(db);
                QString sql="Update IsFirstStartUp set IsFirst='1',GuideStatus=5";
                query.exec(sql);
                query.clear();

                refShadeWindow();
            });

            QPushButton *btnSet=new QPushButton("新建(N)",mpShadeWindow);
            btnSet->setGeometry(btnRect.x(),screenHeight-60,120,40);
            QFont btnFont=btnSet->font();
            font.setPointSize(12);
            btnSet->setFont(font);
#ifdef Q_OS_ANDROID
    int fontId = QFontDatabase::addApplicationFont(":/FontStyle/AlibabaPuHuiTi-3-55-Regular.ttf");
    if (fontId != -1) {
        QStringList fontFamilies = QFontDatabase::applicationFontFamilies(fontId);
        if (!fontFamilies.isEmpty()) {
            QString familyName = fontFamilies.first();
            QFont font(familyName, 18); // 创建一个QFont对象，设置字体名称和默认大小
            btnSet->setFont(font);

        }
    }
#endif
            btnSet->setStyleSheet("background-color: qlineargradient(x1: 0, y0: 0, x2: 0, y2: 1, stop: 0 #8C97ED, stop: 1 #0018D1);border-radius: 8px; color: white;");

            QLabel *movieLabel=new QLabel("",mpShadeWindow);
            movieLabel->setGeometry(btnRect.x(),screenHeight-40,60,60);
            movieLabel->setStyleSheet("background-color:rgba(0,0,0,0);");

            QMovie  *guideMovie = new QMovie(":/pic/picture/guide.gif");
            movieLabel->setMovie(guideMovie);
            guideMovie->start();

            QObject::connect(btnSet, &QPushButton::clicked,[this](){
                on_addAmplStepBtn_clicked();
            });

            mpShadeWindow->show();
        }
    }
}

void amplprogramwindow::on_addAmplStepBtn_clicked()
{
    this->hide();
    emit changeAmplStepWindow("");
}

//返回主页面
void amplprogramwindow::on_returnMainWinBtn_clicked()
{
    this->close();
    emit changeMainWindow();
}

//删除
void amplprogramwindow::delBtnClicked(){
    QMessageBox *box = new QMessageBox(QMessageBox::Question, "提示", "确认删除当前扩增程序", QMessageBox::Yes|QMessageBox::No, this);
    box->button(QMessageBox::Yes)->setText("确认");// 将原本显示“Yes”的按钮改为显示“确认”
    box->button(QMessageBox::No)->setText("取消");// 将原本显示“Yes”的按钮改为显示“确认”

    int res= box->exec();
    if(QMessageBox::Yes == res)
    {
        QSqlDatabase db = dbHelper::openConnection();
        QSqlQuery query(db);

        QPushButton *btn = (QPushButton*)sender();
        QWidget *w_parent = (QWidget*)btn->parent();
        int x = w_parent->frameGeometry().x();
        int y = w_parent->frameGeometry().y();
        QModelIndex index = ui->tableWidget->indexAt(QPoint(x,y));

        QString id = ui->tableWidget->item(index.row(),0)->text();//取出当前行第1列内容
        QString sql=QString("Delete from AmplProgram where id='%1'").arg(id);
        query.exec(sql);

        sql=QString("Delete from AmplStep where ProgramId='%1'").arg(id);
        query.exec(sql);

        RefreshTableData();
    }
}

//设置默认
void amplprogramwindow::defaultBtnClicked(){
    QPushButton *btn = (QPushButton*)sender();
    QWidget *w_parent = (QWidget*)btn->parent();
    int x = w_parent->frameGeometry().x();
    int y = w_parent->frameGeometry().y();
    QModelIndex index = ui->tableWidget->indexAt(QPoint(x,y));

    if(btn->text()=="取消默认")
    {
        QMessageBox *box = new QMessageBox(QMessageBox::Question, "提示", "是否取消默认程序", QMessageBox::Yes|QMessageBox::No, this);
        box->button(QMessageBox::Yes)->setText("确认");// 将原本显示“Yes”的按钮改为显示“确认”
        box->button(QMessageBox::No)->setText("取消");// 将原本显示“Yes”的按钮改为显示“确认”
        int res= box->exec();

        if(QMessageBox::Yes == res){
            QSqlDatabase db = dbHelper::openConnection();
            QSqlQuery query(db);

            QString id=ui->tableWidget->item(index.row(),0)->text();
            QString sql=QString("Update AmplProgram set IsDefault='False' where id='%1'").arg(id);
            query.exec(sql);
            RefreshTableData();
        }
    }
    else{
        QString id=ui->tableWidget->item(index.row(),0)->text();
        QSqlDatabase db = dbHelper::openConnection();
        QSqlQuery query(db);
        QString sql=QString("Update AmplProgram set IsDefault='False'");
        query.exec(sql);

        sql=QString("Update AmplProgram set IsDefault='True' where id='%1'").arg(id);
        query.exec(sql);
        RefreshTableData();
    }
}

//点击查看按钮
void amplprogramwindow::viewBtnClicked(){
    QPushButton *btn = (QPushButton*)sender();
    QWidget *w_parent = (QWidget*)btn->parent();
    int x = w_parent->frameGeometry().x();
    int y = w_parent->frameGeometry().y();
    QModelIndex index = ui->tableWidget->indexAt(QPoint(x,y));

    QString id = ui->tableWidget->item(index.row(),0)->text();//取出当前行第1列内容
    this->hide();
    emit changeAmplStepReadWindow(id);

}

//刷新表格数据
void amplprogramwindow::RefreshTableData(){
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);

    ui->tableWidget->setRowCount(0);
    int rowNum=0;
    QList<QString> lableList;
    lableList<<"Id"<<"IsDefault"<<"ProgramName"<<"Duration"<<"StepNum"<<"HotCoverTemp"<<"CreateDate"<<"Memo";

    query.exec("Select * from AmplProgram");

    while (query.next()) {
        ui->tableWidget->insertRow(rowNum);
        ui->tableWidget->setRowHeight(rowNum, 50);

        QPushButton *delBtn = new QPushButton();
        delBtn->setText("删除");
        delBtn->setMinimumSize(50,40);
        QPushButton *defaultBtn = new QPushButton();
        defaultBtn->setText("默认");
        defaultBtn->setMinimumSize(50,40);
        QPushButton *viewBtn = new QPushButton();
        viewBtn->setText("查看");
        viewBtn->setMinimumSize(50,40);
#ifdef Q_OS_ANDROID
    int fontId = QFontDatabase::addApplicationFont(":/FontStyle/AlibabaPuHuiTi-3-55-Regular.ttf");
    if (fontId != -1) {
        QStringList fontFamilies = QFontDatabase::applicationFontFamilies(fontId);
        if (!fontFamilies.isEmpty()) {
            QString familyName = fontFamilies.first();
            QFont font(familyName, 18); // 创建一个QFont对象，设置字体名称和默认大小
            delBtn->setFont(font);
            defaultBtn->setFont(font);
            viewBtn->setFont(font);

        }
    }
#endif

        QWidget *tmp_widget = new QWidget();
        QHBoxLayout *tmp_layout = new QHBoxLayout(tmp_widget);

        tmp_layout->addWidget(delBtn);
        tmp_layout->addWidget(defaultBtn);
        tmp_layout->addWidget(viewBtn);
        tmp_layout->setMargin(0);
        ui->tableWidget->setCellWidget(rowNum,8,tmp_widget);

        connect(delBtn, SIGNAL(clicked()), this,SLOT(delBtnClicked()));
        connect(defaultBtn, SIGNAL(clicked()), this,SLOT(defaultBtnClicked()));
        connect(viewBtn, SIGNAL(clicked()), this,SLOT(viewBtnClicked()));

        for (int col = 0; col < lableList.length(); col++) {
            QTableWidgetItem *item = new QTableWidgetItem(query.value(lableList[col]).toString());
            item->setFlags(item->flags() & ~Qt::ItemIsEnabled);
            ui->tableWidget->setItem(rowNum, col, item);
        }

        if(query.value("IsDefault")=="True"){
            TriangleCornerLabel3 *label = new TriangleCornerLabel3();
            ui->tableWidget->setCellWidget(rowNum,2,label);
            label->setText(query.value("ProgramName").toString());
            defaultBtn->setText("取消默认");
            defaultBtn->setStyleSheet("background-color: rgb(173, 216, 230);");
        }

        rowNum++;
    }
    query.clear();
}

void amplprogramwindow::on_pushButton_5_clicked()
{
    try{
        if(doorStatus.get()==0)
        {
            doorStatus.set(1);
            ui->pushButton_5->setText("        关闭仓门");
        }
        else
        {
            doorStatus.set(0);
            ui->pushButton_5->setText("        打开仓门");
        }
    }
    catch(std::exception &e){
        QString err=e.what();
        logClient->WriteLog("Exception","刷新扩增程序列表异常:"+err);
    }
    catch(...)
    {
        logClient->WriteLog("Exception","刷新扩增程序列表捕获到未知异常;");
    }
}

//全部删除
void amplprogramwindow::on_pushButton_clicked()
{
    QMessageBox *box = new QMessageBox(QMessageBox::Question, "提示", "确认删除所有扩增程序", QMessageBox::Yes|QMessageBox::No, this);
    box->button(QMessageBox::Yes)->setText("确认");// 将原本显示“Yes”的按钮改为显示“确认”
    box->button(QMessageBox::No)->setText("取消");// 将原本显示“Yes”的按钮改为显示“确认”

    int res= box->exec();
    if(QMessageBox::Yes == res)
    {
        QSqlDatabase db = dbHelper::openConnection();
        QSqlQuery query(db);

        QString sql="Delete From AmplProgram";
        query.exec(sql);

        sql ="Delete From AmplStep";
        query.exec(sql);

        RefreshTableData();
    }
}

void TriangleCornerLabel3::paintEvent(QPaintEvent *event)
{
    QLabel::paintEvent(event);

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    // 设置三角形的颜色和样式
    painter.setPen(Qt::NoPen);
    painter.setBrush(Qt::darkBlue);

    // 计算三角形的顶点位置
    QPoint p1(this->width()-30, this->height()); // 左上角顶点
    QPoint p2(this->width(), this->height()); // 右上角顶点
    QPoint p3(this->width(), this->height()-30); // 左下角顶点

    // 绘制三角形
    QPainterPath path;
    path.moveTo(p1);
    path.lineTo(p2);
    path.lineTo(p3);
    path.closeSubpath();
    painter.drawPath(path);

    // 设置字体样式和大小
    painter.setPen(Qt::white); // 设置文本颜色为白色
    // 假设字体大小是三角形大小的一半（或根据需要调整）
    painter.setFont(QFont("Arial", 8, QFont::Bold));
    // 计算文本位置
    QPoint textTopLeft(this->width()-13,this->height()-7); // 确保文本在三角形内部并靠近上边缘
    // 绘制文本
    painter.drawText(textTopLeft, "默");
}

